import axios from 'axios'
import store from '../store'
import router from '../router'

// 请求拦截器
axios.interceptors.request.use(
  config => {
    const token = store.state.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response && error.response.status === 401) {
      // 身份验证失败，清除token并跳转登录页
      store.dispatch('logout')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)